<template>
  <div class="container">
    <el-dialog
      :title="addDialog.dialogType === 'edit' ? '修改调拨单' : '添加调拨单'"
      :visible.sync="addDialog.centerDialogVisible"
      @open="openData"
      @close="cancel"
      center
      width="99%"
    >
      <div class="top">
        <div style="margin-bottom: 5px">
          <el-select
            :multiple="false"
            filterable
            remote
            center
            reserve-keyword
            v-model="selectList"
            placeholder="选择调入配送中心"
            :remote-method="selectListsRemoteMethod"
            :loading="selectLists.loading"
          >
            <el-option
              v-for="item in selectLists.option"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <div style="margin-bottom: 5px">
          <el-switch
            v-model="is_sale"
            active-text="销售调拨单"
            inactive-text="普通调拨单"
          >
          </el-switch>
        </div>
        <el-select
          v-model="procurement.value"
          :multiple="false"
          filterable
          remote
          reserve-keyword
          placeholder="请选择调入采购员"
          :remote-method="insideProcurement"
          :loading="procurement.loading"
          @change="insidebuyer(procurement.value)"
        >
          <el-option
            v-for="item in procurement.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>

      <div class="top">
        <el-select
          style="width: 50%"
          multiple
          filterable
          remote
          center
          reserve-keyword
          v-model="commodity"
          placeholder="商品编码/商品名称/仓库名称"
          :remote-method="insideRemoteMethod"
          :loading="inside.loading"
          @change="commodityChange(commodity)"
        >
          <el-option
            v-for="item in inside.option"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"
          ></el-option>
        </el-select>
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-search"
          @click="addGoods()"
          >添加</el-button
        >
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-upload"
          @click="download()"
          >模板下载</el-button
        >

        <el-upload
          class="upload-demo"
          style="display: inline; margin-left: 10px"
          action="#"
          :show-file-list="false"
          :http-request="handleAvatarSuccess"
        >
          <el-button
            size="medium"
            type="primary"
            class="handleSearch"
            icon="el-icon-circle-plus"
            >导入商品</el-button
          >
        </el-upload>
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="code"
          label="批次编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="erp_goods_code"
          label="商品编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="goods_bar_code"
          label="商品条码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="goods_name"
          label="商品名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="category_name"
          label="品类名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="category_code"
          label="品类编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="unit"
          label="商品单位"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="spec"
          label="商品规格"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="whsecode"
          label="调出仓库编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="whsename"
          label="调出仓库名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="stock_num"
          label="库存数量"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="price"
          label="调拨成本 "
          align="center"
        ></el-table-column>
        <!-- 成本+加价 -->
        <el-table-column
          prop="goods_price"
          label="调拨单价"
          align="center"
        ></el-table-column>
        <el-table-column label="批次" align="center" width="160">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.code"
              @change="onBatch(scope)"
              placeholder="请选择批次"
            >
              <el-option
                v-for="item in scope.row.batchList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="调拨数量" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              :min="0"
              size="small"
              :controls="false"
              v-model="scope.row.goods_num"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="调拨加价" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @blur="totalPrices(scope)"
              :controls="false"
              v-model="scope.row.markup"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="danger"
              @click="remove(scope)"
              icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  selectAllocationBatchData,
  addAllocationInfo,
  findAllocationInfo,
  editAllocationInfo,
} from "@/api/superAllot/superAllotList";
import { getToken } from "@/utils/auth";
import { Loading } from "element-ui";
import { selectRdcData } from "@/api/select/select";
import { getList } from "@/api/putStorage/putStotageList";
export default {
  props: {
    addDialog: Object,
  },
  data() {
    return {
       is_sale: false,
      tableData: [],
      goodsList: [],
      insideList: [],
      commodity: "",
      procurement: {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      },
      buyer: {
        name: "",
        code: "",
        id: "",
      },
      inside: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },
      selectLists: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },

      selectList: "",
    };
  },
  methods: {
    //取消
    cancel() {
      this.addDialog.centerDialogVisible = false;
      this.tableData = [];
      this.goodsList = [];
      this.commodity = "";
      this.procurement = {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      };
      this.buyer = {
        name: "",
        code: "",
        id: "",
      };
      this.inside = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      };
      this.selectLists = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      };

      this.selectList = "";
    },
    getData() {
      if (this.addDialog.dialogType == "edit") {
        let data = {
          id: this.addDialog.id,
        };
        findAllocationInfo(data).then((res) => {
          if (res.code == 0) {
            this.selectList = res.data.info.inp_rdc_code;
            this.buyer.id = res.data.info.inp_buyer_id;
            this.buyer.code = res.data.info.inp_buyer_code;
            this.buyer.name = res.data.info.inp_buyer_name;
            this.procurement.value = res.data.info.inp_buyer_name;
            this.is_sale = res.data.info.is_sale ? true : false;
            res.data.goods.forEach((item) => {
              item.batchList = [];
              item.batchlist.forEach((prop) => [
                item.batchList.push({
                  value: `${prop.code}`,
                  label: `${prop.goods_name}【${prop.code}】(${prop.stock_num}/${prop.rk_spec})${prop.whsename}`,
                  obj: prop,
                }),
              ]);
              item.goods_bar_code = item.bar_code;
              item.code = item.batch_code;
              item.unit = item.goods_unit;
              item.spec = item.goods_spec;
              item.whsecode = item.out_house_code;
              item.whsename = item.out_house_name;
              item.stock_num = item.stock_num;
              item.price = item.goods_cost;
            });
            this.tableData = res.data.goods;
          }
        });
      }
    },
    getBatch(query = "") {
      let data = {
        keyword: query,
      };
      //获取批次
      selectAllocationBatchData(data).then((res) => {
        this.goodsList = res.data.list;
        this.inside.option = res.data.list.map((item) => {
          if (this.tableData.length > 0) {
            let arr = this.tableData.filter((prop) => {
              return prop.code == item.code;
            });

            if (arr.length > 0) {
              return {
                disabled: true,
                value: `${item.code}`,
                label: `${item.goods_name}【${item.code}】(${item.stock_num}/${item.rk_spec})${item.whsename}`,
              };
            } else {
              return {
                value: `${item.code}`,
                label: `${item.goods_name}【${item.code}】(${item.stock_num}/${item.rk_spec})${item.whsename}`,
              };
            }
          } else {
            return {
              value: `${item.code}`,
              label: `${item.goods_name}【${item.code}】(${item.stock_num}/${item.rk_spec})${item.whsename}`,
            };
          }
        });
      });
    },
    openData() {
      this.getselsetData();
      this.getBatch();
      this.purchase();
      this.getData();
    },
    purchase() {
      let datas = {
        key: "",
      };
      //获取采购员
      getList(datas).then((res) => {
        this.procurement.options = res.data.map((item) => {
          return {
            value: `${item.code}`,
            label: `${item.name}(${item.code})`,
            id: `${item.id}`,
          };
        });
        this.procurementList = res.data;
      });
    },

    getselsetData(query = "") {
      let data = {
        page: 1,
        limit: 500,
        code_or_name: query,
      };
      //获取配送中心
      selectRdcData(data).then((res) => {
        if (res.data.paginate.data) {
          this.selectLists.option = res.data.paginate.data.map((item) => {
            return {
              value: `${item.d_code}`,
              label: `${item.d_name}`,
            };
          });
        }
      });
    },

    // 嵌套搜索配送方式数据
    selectListsRemoteMethod(query) {
      if (query !== "") {
        this.houseList(query);
      } else {
        this.selectLists.option = [];
      }
    },
    //获取配送数据
    houseList(query) {
      if (query !== "") {
        this.getselsetData(query);
      } else {
        this.procurement.options = [];
      }
    },

    //获取采购员name,code,id
    insidebuyer(e) {
      let center = this.procurementList.filter((res) => {
        return res.code == e;
      });
      this.buyer = {
        name: center[0].name,
        code: center[0].code,
        id: center[0].id,
      };
    },
    //搜索采购员
    insideProcurement(query) {
      if (query !== "") {
        this.getProcurement(query);
      } else {
        this.procurement.options = [];
      }
    },
    //获取采购员列表
    getProcurement(query) {
      let data = {
        key: query,
      };
      this.procurement.loading = true;
      getList(data).then((res) => {
        this.procurement.list = res.data.map((item) => {
          return {
            value: `${item.code}`,
            label: `${item.name}(${item.code})`,
            id: `${item.id}`,
          };
        });
        this.procurement.loading = false;
        this.procurement.options = this.procurement.list.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.procurementList = res.data;
      });
    },

    //删除
    remove(scope) {
      let index = scope.$index;
      this.tableData.splice(index, 1);
      this.getBatch();
    },
    commodityChange(scope) {
      if (this.insideList.length > 0) {
        if (scope.length < this.insideList.length) {
          this.insideList.forEach((res, index) => {
            if (res.code != scope[index]) {
              this.insideList.splice(index, 1);
            }
          });
        } else {
          let arr = this.goodsList.filter((res) => {
            return res.code == scope[scope.length - 1];
          });
          this.insideList.push(arr[0]);
        }
      } else {
        let arr = this.goodsList.filter((res) => {
          return res.code == scope[0];
        });
        this.insideList.push(arr[0]);
      }
    },
    //选择批次
    onBatch(scope) {
      console.log(scope.row, 999999);
      let boolArr = this.tableData.filter((res) => {
        return res.orgCode == scope.row.code;
      });
      if (boolArr.length > 0) {
        this.tableData[scope.$index].code =
          this.tableData[scope.$index].orgCode;
        this.$message({
          type: "info",
          message: "该批次已添加",
        });
      } else {
        let arrObj = scope.row.batchList.filter((res) => {
          return res.value == scope.row.code;
        });
        this.tableData[scope.$index].id = 0;
        this.tableData[scope.$index].markup = arrObj[0].obj.allocation_markup;
        this.tableData[scope.$index].goods_price =
          (parseFloat(arrObj[0].obj.price) +
          parseFloat(arrObj[0].obj.allocation_markup)).toFixed(2);
        // console.log(this.tableData[scope.$index].goods_price,8989898)
        this.tableData[scope.$index].orgCode = arrObj[0].obj.code;
        this.tableData[scope.$index].erp_goods_code =
          arrObj[0].obj.erp_goods_code;
        this.tableData[scope.$index].goods_bar_code =
          arrObj[0].obj.goods_bar_code;
        this.tableData[scope.$index].batch_id = arrObj[0].obj.id;
        this.tableData[scope.$index].goods_name = arrObj[0].obj.goods_name;
        this.tableData[scope.$index].category_name =
          arrObj[0].obj.category_name;
        this.tableData[scope.$index].category_code =
          arrObj[0].obj.category_code;
        this.tableData[scope.$index].unit = arrObj[0].obj.unit;
        this.tableData[scope.$index].spec = arrObj[0].obj.spec;
        this.tableData[scope.$index].whsecode = arrObj[0].obj.whsecode;
        this.tableData[scope.$index].whsename = arrObj[0].obj.whsename;
        this.tableData[scope.$index].stock_num = arrObj[0].obj.stock_num;
        this.tableData[scope.$index].price = arrObj[0].obj.price;
        this.getBatch();
      }
    },
    // 添加商品
    addGoods() {
      if (this.insideList.length > 0) {
        this.insideList.forEach((res) => {
          res.goods_num = 0;
          res.markup = res.allocation_markup;
          res.batch_id = res.id;
          res.orgCode = res.code;
          res.id = 0;
          res.goods_price =
            (parseFloat(res.price) + parseFloat(res.allocation_markup)).toFixed(2);
          res.batchList = [];
          res.batchlist.forEach((prop) => [
            res.batchList.push({
              value: `${prop.code}`,
              label: `${prop.goods_name}【${prop.code}】(${prop.stock_num}/${prop.rk_spec})${prop.whsename}`,
              obj: prop,
            }),
          ]);
          this.tableData.push(res);
        });
      } else {
        this.$message({
          type: "info",
          message: "请选择商品",
        });
      }
      this.insideList = [];
      this.commodity = [];
      this.getBatch();
      // if (this.commodity) {
      //   let every = this.tableData.filter((res) => {
      //     return res.code == this.commodity;
      //   });
      //   if (every.length == 0) {
      //     let arr = this.goodsList.filter((res) => {
      //       return res.code == this.commodity;
      //     });
      //     console.log(arr, 7777);
      //     arr[0].goods_num = 0;
      //     arr[0].markup = arr[0].allocation_markup;
      //     arr[0].batch_id = arr[0].id;
      //     arr[0].id = 0;
      //     arr[0].goods_price =
      //       parseFloat(arr[0].price) + parseFloat(arr[0].allocation_markup);
      //     this.tableData.push(arr[0]);
      //   } else {
      //     this.$message({
      //       type: "info",
      //       message: "该商品已添加",
      //     });
      //   }
      // } else {
      //   this.$message({
      //     type: "info",
      //     message: "请选择商品",
      //   });
      // }
    },

    // 获取批次方法
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getBatch(query);
      } else {
        this.inside.options = [];
      }
    },
    //修改调拨加价
    totalPrices(scope) {
      if (scope.row.markup != null || scope.row.markup != undefined) {
        scope.row.goods_price =
          (parseFloat(scope.row.markup) + parseFloat(scope.row.price)).toFixed(2);
      } else {
        scope.row.markup = 0;
        scope.row.goods_price =
          (parseFloat(scope.row.markup) + parseFloat(scope.row.price)).toFixed(2);
      }

      this.$set(this.tableData, scope.$index, scope.row);
    },
    //下载模板
    download() {
      this.$confirm("是否下载模板?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/Allocation/downloadTemplte?token=" +
            getToken();
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    //导入商品
    handleAvatarSuccess(param) {
      let loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
      });
      let data = new window.FormData();
      data.append("goods_file", param.file);
      data.append("token", getToken());

      this.$axios
        .post("/smkapi/Allocation/importAllocationGoods", data)
        .then((res) => {
          loading.close();
          if (res.data.code == 0) {
            // this.tableData = [];
            console.log(res, 8888);
            res.data.data.list.forEach((scope) => {
              console.log(scope, 8888);
              scope.batchLists = [];
              scope.batchlist.forEach((prop) => [
                scope.batchLists.push({
                  value: `${prop.code}`,
                  label: `${prop.goods_name}【${prop.code}】(${prop.stock_num}/${prop.rk_spec})${prop.whsename}`,
                  obj: prop,
                }),
              ]);
              this.tableData.push({
                erp_goods_code: scope.erp_goods_code,
                goods_name: scope.goods_name,
                goods_num: scope.goods_num,
                markup: scope.allocation_markup,
                batchList: scope.batchLists,
              });
            });
          } else {
            this.$message({
              type: "info",
              message: res.data.message || res.data.msg,
            });
          }
        });
    },
    //确定
    confirm() {
      if (this.buyer.code == "") {
        this.$message({
          type: "info",
          message: "请选择采购员",
        });
      } else if (this.selectList == "") {
        this.$message({
          type: "info",
          message: "请选择配送中心",
        });
      } else if (this.tableData.length == "") {
        this.$message({
          type: "info",
          message: "请添加批次",
        });
      } else {
        let arr = this.tableData.filter((prop) => {
          return prop.goods_num == "0" || prop.goods_num == 0;
        });
        if (arr.length > 0) {
          this.$message({
            type: "info",
            message: "调拨数量不能为0",
          });
        } else {
          if (this.addDialog.dialogType == "edit") {
            let arr = [];
            this.tableData.forEach((res) => {
              arr.push({
                batch_id: res.batch_id,
                goods_num: res.goods_num,
                markup: res.markup,
                id: res.id,
              });
            });

            let data = {
              id: this.addDialog.id,
              inp_rdc_code: this.selectList,
              goods: JSON.stringify(arr),
              inp_buyer_id: this.buyer.id,
              inp_buyer_code: this.buyer.code,
              inp_buyer_name: this.buyer.name,
                is_sale: this.is_sale ? 1 : 0,
            };
            editAllocationInfo(data).then((res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: res.msg || res.message,
                });
                this.$emit("upData");
                this.cancel();
              }
            });
          } else {
            let arr = [];
            this.tableData.forEach((res) => {
              arr.push({
                batch_id: res.batch_id,
                goods_num: res.goods_num,
                markup: res.markup,
                id: 0,
              });
            });

            let data = {
              inp_rdc_code: this.selectList,
              goods: JSON.stringify(arr),
              inp_buyer_id: this.buyer.id,
              inp_buyer_code: this.buyer.code,
              inp_buyer_name: this.buyer.name,
                is_sale: this.is_sale ? 1 : 0,
            };
            addAllocationInfo(data).then((res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: res.msg || res.message,
                });
                this.$emit("upData");
                this.cancel();
              }
            });
          }
        }
      }
    },
  },
};
</script>
<style scoped>
.pagination {
  text-align: right;
  padding: 10px;
}
.top {
  margin-bottom: 5px;
}
</style>
